package jjn.acwing;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author Jiang Jining
 * @since 2023-09-17 10:17
 */
public class Acwing3375 {
    static class Student {
        int score;
        String name;
        int order;
        
        public String toString() {
            return String.format("%s %d", name, score);
        }
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int n = scanner.nextInt();
            int order = scanner.nextInt();
            List<Student> students = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                Student student = new Student();
                student.name = scanner.next();
                student.score = scanner.nextInt();
                student.order = i;
                students.add(student);
            }
            int weight = (order == 0) ? 1 : -1;
            students.sort((s1, s2) -> {
                if (s1.score == s2.score) {
                    return Integer.compare(s1.order, s2.order);
                }
                if (s1.score < s2.score) {
                    return weight;
                }
                return -1 * weight;
            });
            students.forEach(System.out::println);
        }
    }
}
